﻿using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.IO;
using System.Text;
using System.Windows.Input;
using DataStore;
using DataStore.Domain;
using DataStore.Repositories;
using ExportWordBibModule.SchemaImplementation;
using Infrastructure.CurrentData;
using Infrastructure.Services;
using log4net;
using Microsoft.Practices.Composite.Modularity;
using Microsoft.Practices.Composite.Regions;
using Microsoft.Practices.Unity;
using Microsoft.Windows.Controls.Ribbon;
using Microsoft.WindowsAPICodePack.Dialogs;
using Author=ExportWordBibModule.SchemaImplementation.Author;

namespace ExportWordBibModule
{
    /// <summary>
    /// Exporter module
    /// Exports book list to Word 2007 Bibliography format
    /// </summary>
    [Module(ModuleName = "ExportWordBibModule")]
    public class ExportWordBibModule : IModule
    {
        private readonly IRegionManager _regionManager;
        readonly IUnityContainer _container;
        IDatabase _database;

        /// <summary>
        /// Initializes a new instance of the <see cref="ExportWordBibModule"/> class.
        /// </summary>
        /// <param name="container">The container.</param>
        /// <param name="regionManager">The region manager.</param>
        public ExportWordBibModule(IUnityContainer container, IRegionManager regionManager)
        {
            _container = container;
            _regionManager = regionManager;
        }

        /// <summary>
        /// Registers the views with regions.
        /// </summary>
        void RegisterViewsWithRegions()
        {
        }

        /// <summary>
        /// Registers the types and services.
        /// </summary>
        void RegisterTypesAndServices()
        {
        }

        /// <summary>
        /// Registers the export menu.
        /// </summary>
        void RegisterExportMenu()
        {
            RibbonApplicationSplitMenuItem menuItem = new RibbonApplicationSplitMenuItem();
            RibbonCommand command = new RibbonCommand()
                                        {
                                            LabelTitle = "Word Bibliography",
                                        };
            command.Executed += WinBibExportPressed;
            menuItem.Command = command;

            var ribbonService = _container.Resolve<IRibbonService>();
            ribbonService.AddSplitMenuItem(RibbonMenu.ExportList, menuItem);
        }

        /// <summary>
        /// Wins the bib export pressed.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="args">The <see cref="System.Windows.Input.ExecutedRoutedEventArgs"/> instance containing the event data.</param>
        void WinBibExportPressed(object sender, ExecutedRoutedEventArgs args)
        {
            CommonSaveFileDialog dialog = new CommonSaveFileDialog("BioExport")
                                              {
                                                  DefaultExtension = "xml",
                                                  EnsurePathExists = true,
                                                  EnsureValidNames = true,
                                                  Title = "Export to Word Bibliography"
                                              };
            dialog.Filters.Add(new CommonFileDialogFilter("XML", ".xml"));
            if(dialog.ShowDialog() == CommonFileDialogResult.OK)
            {
                Export(dialog.FileName);
            }
        }

        #region Implementation of IModule

        /// <summary>
        /// Notifies the module that it has be initialized.
        /// </summary>
        public void Initialize()
        {
            ILog log = _container.Resolve<ILog>();
            log.Info("ExportWordBibModule loaded");

            _database = Current.Container.Resolve<IDatabase>();

            RegisterTypesAndServices();
            RegisterViewsWithRegions();
            RegisterExportMenu();
        }

        

        #endregion

        /// <summary>
        /// Exports the book list to specified export path.
        /// </summary>
        /// <param name="exportPath">The export path.</param>
        void Export(string exportPath)
        {
            Contract.Requires(!string.IsNullOrEmpty(exportPath));
            Contract.Ensures(File.Exists(exportPath));

            // Generate XML
            Sources sources = new Sources();
            using (UnitOfWork unitOfWork = _database.CreateUnitOfWork())
            {
                IRepository<CatalogItem> repository = new CatalogItemRepository(unitOfWork);
                IEnumerable<CatalogItem> items = repository.All;


                foreach (var item in items)
                {
                    Source source = new Source();
                    source.BookTitle = item.Title;
                    foreach (var author in item.Authors)
                    {
                        Author eAuthor = new Author();
                        eAuthor.First = author.FirstName;
                        eAuthor.Last = author.LastName;
                        source.Authors.Add(eAuthor);
                    }

                    sources.Source.Add(source);
                }
            }
            var s = sources.Render();

            // Write XML
            using (StreamWriter writer = new StreamWriter(exportPath, false, Encoding.UTF8))
            {
                writer.Write(s);
            }
        }
    }
}
